<template>
  <div style="width: 100%;" class="card-area">
    <layout-content topTitle="查询" bottomTitle="用户信息">
      <template v-slot:topCard>
        <a-form layout="horizontal">
          <a-row>
            <a-col :md="6" :sm="24">
              <a-form-item label="用户名" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18, offset: 0 }">
                <a-input size="small" v-model="queryParams.username" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="状态" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18, offset: 0 }">
                <a-select size="small" :allowClear="true" v-model="queryParams.stat">
                  <a-select-option key="0" value=0>系统锁定</a-select-option>
                  <a-select-option key="1" value=1>有效</a-select-option>
                  <a-select-option key="2" value=2>IDM禁用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <span style="float: left; margin-top: 8px;margin-left: 3rem">
              <a-button type="primary" @click="search">查询</a-button>
              <a-button @click="reset">重置</a-button>
            </span>
          </a-row>
        </a-form>
      </template>
      <template v-slot:extraOperation>
        <a-button v-hasPermission="'user:add'" type="primary" @click="add">
          <icon-font type="iconicon-test1" />新增
        </a-button>
      </template>
      <template v-slot:bottomCard>
        <!-- 表格区域 -->
        <a-table
          ref="TableInfo"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="pagination"
          :loading="loading"
          :scroll="{ x: 1080 }"
          @change="handleTableChange"
        >
          <template slot="operation" slot-scope="text, record">
            <div v-if="showEdit(record)">
              <icon-font v-hasPermission="'user:view'" type="iconchakan" @click="view(record)" title="查看" />
              <span>|</span>
              <icon-font
                v-hasPermission="'user:update'"
                type="iconbianji1"
                theme="twoTone"
                twoToneColor="#4a9ff5"
                @click="edit(record)"
                title="编辑"
              />
              <span>|</span>
              <icon-font v-hasPermission="'user:delete'" type="iconshanchu1" @click="deleteUser(record)" title="删除" />
            </div>
            <a-badge v-else
              status="warning"
              text="无权限"
            ></a-badge>
          </template>
        </a-table>
        <!-- 用户信息查看 -->
        <user-info :userInfoData="userInfo.data" :userInfoVisiable="userInfo.visiable" @close="handleUserInfoClose">
        </user-info>
        <!-- 新增用户 -->
        <user-add @close="handleUserAddClose" @success="handleUserAddSuccess" :userAddVisiable="userAdd.visiable">
        </user-add>
        <!-- 修改用户 -->
        <user-edit
          ref="userEdit"
          @close="handleUserEditClose"
          @success="handleUserEditSuccess"
          :userEditVisiable="userEdit.visiable"
        >
        </user-edit>
      </template>
    </layout-content>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import UserInfo from './UserInfo';
import UserAdd from './UserAdd';
import UserEdit from './UserEdit';
import layoutContent from '@/components/tool/layout-content';

export default {
  name: 'User',
  components: { UserInfo, UserAdd, UserEdit, layoutContent },
  data() {
    return {
      advanced: false,
      userInfo: {
        visiable: false,
        data: {}
      },
      userAdd: {
        visiable: false
      },
      userEdit: {
        visiable: false
      },
      queryParams: {},
      filteredInfo: null,
      sortedInfo: null,
      paginationInfo: null,
      dataSource: [],
      loading: false,
      pagination: {
        size: 'small',
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      }
    };
  },
  computed: {
    ...mapState({
      user: state => state.account.user
    }),
    columns() {
      let { sortedInfo, filteredInfo } = this;
      sortedInfo = sortedInfo || {};
      filteredInfo = filteredInfo || {};
      return [
        {
          title: '用户名',
          align: 'center',
          dataIndex: 'username',
          width: 120
        },
        {
          title: '性别',
          dataIndex: 'ssex',
          width: 80,
          customRender: (text, row, index) => {
            switch (text) {
              case 1:
                return '男';
              case 2:
                return '女';
              case 3:
                return '保密';
              default:
                return '保密';
            }
          }
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          width: 100
        },
        {
          title: '电话',
          dataIndex: 'mobile',
          width: 100
        },
        {
          title: '状态',
          dataIndex: 'stat',
          width: 100,
          customRender: (text, row, index) => {
            switch (
              text //0 系统锁定 1有效 2 IDM禁用(ds-pwp-account-disabled=true）
            ) {
              case 0:
                return <a-tag color="cyan">有效</a-tag>;
              case 1:
                return <a-tag color="red">锁定</a-tag>;
              case 2:
                return <a-tag color="red">禁用</a-tag>;
              default:
                return ''+text;
            }
          }
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 140
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
          width: 140
        }
      ];
    }
  },
  mounted() {
    this.fetch();
  },
  methods: {
    showEdit(user) {
        if (this.user.roleCode === "admin"){
            return true;
        }
        if ("admin" === user.roleCode || "system" ===  user.roleCode  ) {
          return false;
        }
        return true;
    },
    view(record) {
      this.userInfo.data = record;
      this.userInfo.visiable = true;
    },
    add() {
      this.userAdd.visiable = true;
    },
    handleUserAddClose() {
      this.userAdd.visiable = false;
    },
    handleUserAddSuccess() {
      this.userAdd.visiable = false;
      this.$message.success('新增用户成功');
      this.search();
    },
    edit(record) {
      this.$refs.userEdit.setFormValues(record);
      this.userEdit.visiable = true;
    },
    handleUserEditClose() {
      this.userEdit.visiable = false;
    },
    handleUserEditSuccess() {
      this.userEdit.visiable = false;
      this.$message.success('修改用户成功');
      this.search();
    },
    handleUserInfoClose() {
      this.userInfo.visiable = false;
    },
    deleteUser(record) {
      if (!record) {
        this.$message.warning('请选择需要删除的记录');
        return;
      }
      let that = this;
      this.$confirm({
        title: '确定删除吗?',
        content: '删除将不能恢复哦！',
        centered: true,
        onOk() {
          that.$delete('user/' + record.userId).then(r => {
            if (r.data.code === 200) {
              that.$message.success('删除成功');
              that.search();
            } else {
              hat.$message.error(r.data.message);
            }
          });
        },
        onCancel() {
          // that.selectedRowKeys = [];
        }
      });
    },
    search() {
      let { sortedInfo, filteredInfo } = this;
      let sortField, sortOrder;
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field;
        sortOrder = sortedInfo.order;
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams,
        ...filteredInfo
      });
    },
    reset() {
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent;
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent;
        this.paginationInfo.pageSize = this.pagination.defaultPageSize;
      }
      // 重置列过滤器规则
      this.filteredInfo = null;
      // 重置列排序规则
      this.sortedInfo = null;
      // 重置查询参数
      this.queryParams = {};
      this.fetch();
    },
    handleTableChange(pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination;
      this.filteredInfo = filters;
      this.sortedInfo = sorter;
      this.userInfo.visiable = false;
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      });
    },
    fetch(params = {}) {
      // 显示loading
      this.loading = true;
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current;
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize;
        params.pageSize = this.paginationInfo.pageSize;
        params.pageNum = this.paginationInfo.current;
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize;
        params.pageNum = this.pagination.defaultCurrent;
      }
      params.userType = 0;
      this.$get('user', {
        ...params
      }).then(r => {
        let data = r.data.data;
        const pagination = { ...this.pagination };
        pagination.total = data.total;
        this.dataSource = data.rows;
        this.pagination = pagination;
        // 数据加载完毕，关闭loading
        this.loading = false;
      });
    }
  }
};
</script>
<style lang="less" scoped>
@import '../../../../static/less/Common';
</style>
